package org.ccheng.xztx.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import io.reactivex.Observable;
import org.ccheng.xztx.domain.News;
import org.ccheng.xztx.domain.NewsHelpStudy;
import org.ccheng.xztx.service.NewsService;
import org.ccheng.xztx.util.Api;
import org.ccheng.xztx.util.ApiConstants;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class NewsServiceImpl implements NewsService {

    public static final String[] ACTIONS = new String[]{"去聚灵", "去帮TA"};

    public News findNews() {
        return findNews(1);
    }

    public News findNews(int pageNo) {
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("pageNo", pageNo);
        return Api.get(ApiConstants.API_NEWS_INDEX, params, News.class);
    }

    /**
     * 执行动作
     *
     * @param study
     */
    public void action(NewsHelpStudy study) {
        for (String action : ACTIONS) {
            if (action.equals(study.getAction())) {
                System.out.println("执行互动[" + study.getAction() + "]");

                Map<String, Object> params = MapUtil.newHashMap();
                params.put("userId", study.getUserId());
                params.put("otherId", study.getUserId());

                String response = Api.get(study.getApi(), params);

                String result = ReUtil.get("(?<=<div class=\"gaps normal\">)\\S{0,20}(?=<br/>)", response, 0);
                String num = ReUtil.get("(?<=次数:)\\S{0,20}(?=<br/>)", response, 0);
                String award = ReUtil.get("(?<=<br/>)(我获得灵气)\\S+(?=<br/>)", response, 0);

                System.out.println("执行结果:" + result);

                if (StrUtil.isNotEmpty(num)) {
                    System.out.println("剩余次数:" + num);
                }
                if (StrUtil.isNotEmpty(award)) {
                    System.out.println(award);
                }
            }
        }
    }

    public void autoHelp() {
        for (int i = 1; i <= 10; i++) {
            autoHelp(i);
        }
    }

    public void autoHelp(int pageNo) {
        News news = findNews(pageNo);

        List<NewsHelpStudy> studyList = news.getStudyList();

        for (NewsHelpStudy study : studyList) {
            action(study);
        }
    }

}
